package org.biouno.unochoice;

import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.model.queue.Tasks;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitTool;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import jenkins.security.FIPS140;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.RemoteConfig;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.GitURIRequirementsBuilder;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;

import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;

import static hudson.Util.fixEmpty;
import static hudson.Util.fixEmptyAndTrim;

@ExportedBean
public class PackageConfig extends AbstractDescribableImpl<PackageConfig> implements Serializable {

    private  String name;
    private  String refspec;
    private  String url;
    private  String credentialsId;
    private  String repositoryName;


    @DataBoundConstructor
    public PackageConfig(String url, String name, String refspec, @CheckForNull String credentialsId, String repositoryName, String jobName) {
        this.url = fixEmptyAndTrim(url);
        this.name = fixEmpty(name);
        this.refspec = fixEmpty(refspec);
        this.credentialsId = fixEmpty(credentialsId);
        if (repositoryName.length() == 0) {
            String[] urls = this.url.split("/");
            this.repositoryName = urls[urls.length - 1].replaceAll(".git", "");
        }else{
            this.repositoryName = repositoryName;
        }
        if (FIPS140.useCompliantAlgorithms() && StringUtils.isNotEmpty(this.credentialsId) && StringUtils.startsWith(this.url, "http:")) {
//            throw new IllegalArgumentException(Messages.git_fips_url_notsecured());
            throw new IllegalArgumentException("credentialsId  error");
        }
    }




    @Exported
    @Whitelisted
    public String getName() {
        return name;
    }

    @Exported
    @Whitelisted
    public String getRepositoryName() {
        return repositoryName;
    }

    @Exported
    @Whitelisted
    public String getRefspec() {
        return refspec;
    }

    @Exported
    @CheckForNull
    @Whitelisted
    public String getUrl() {
        return url;
    }

    @Exported
    @Whitelisted
    @CheckForNull
    public String getCredentialsId() {
        return credentialsId;
    }

    @Override
    public String toString() {
        return getRefspec() + " => " + getUrl() + " (" + getName() + ")";
    }

    private final static Pattern SCP_LIKE = Pattern.compile("(.*):(.*)");


    @Extension
    public static class DescriptorImpl extends Descriptor<PackageConfig> {

        public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project,
                                                     @QueryParameter String url,
                                                     @QueryParameter String credentialsId) {
            if (project == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) ||
                    project != null && !project.hasPermission(Item.EXTENDED_READ)) {
                return new StandardListBoxModel().includeCurrentValue(credentialsId);
            }
            if (project == null) {
                /* Construct a fake project, suppress the deprecation warning because the
                 * replacement for the deprecated API isn't accessible in this context. */
                @SuppressWarnings("deprecation")
                Item fakeProject = new FreeStyleProject(Jenkins.get(), "fake-" + UUID.randomUUID());
                project = fakeProject;
            }
            return new StandardListBoxModel()
                    .includeEmptyValue()
                    .includeMatchingAs(
                            project instanceof Queue.Task t
                                    ? Tasks.getAuthenticationOf(t)
                                    : ACL.SYSTEM,
                            project,
                            StandardUsernameCredentials.class,
                            GitURIRequirementsBuilder.fromUri(url).build(),
                            GitClient.CREDENTIALS_MATCHER)
                    .includeCurrentValue(credentialsId);
        }


        private static StandardCredentials lookupCredentials(@CheckForNull Item project, String credentialId, String uri) {
            return (credentialId == null) ? null : CredentialsMatchers.firstOrNull(
                    CredentialsProvider.lookupCredentialsInItem(StandardCredentials.class, project, ACL.SYSTEM2,
                            GitURIRequirementsBuilder.fromUri(uri).build()),
                    CredentialsMatchers.withId(credentialId));
        }

        @Override
        public String getDisplayName() {
            return "";
        }
    }
}
